var curTabId; //current tab in which scraper is going to scraping
var devtoolPort;
var coord;
var sitemap;
var finish = false;

chrome.browserAction.onClicked.addListener(function() {
	chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
		var tabId = tabs[0].id;
		curTabId = tabId;
		injectScript(tabId);
	});
});



function sendMessage(msg) {
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, msg);
  });
}

//detective devtools
chrome.runtime.onConnect.addListener(function (port) {
    if (port.name == "devtools-papa") {
		devtoolPort = port;
    }
});

//tab update
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
	if(finish === false && coord && changeInfo.status == 'loading'){
		coord.onUpdate(tab);
	}
})

chrome.runtime.onMessage.addListener(function(msg, sender, callback){
	var p = msg.params;
	
	//scrape
	if(msg.cmd == 'START_SCRAPE'){
		var idOrName = p.sitemap;
		//load from db
		chrome.storage.local.get("sitemaps", function(db){
			var _sitemaps = db["sitemaps"];
			if(_sitemaps){
				sitemap = _sitemaps.find(function(s){return s.id == idOrName || s.name == idOrName});
				print(sitemap);
				if(sitemap){
					coord = new Coordinator(sitemap, 20);
					var page = coord.sitemap.pages[0];
					coord.openTab(page.id, page.link);
				}
			}
		});
	}
	else if(msg.cmd == 'SCRAPE_READY'){
		print(sender);
		coord.readyForScrape(sender.tab.id);
	}
	else if(msg.cmd == 'TAB_CLICK'){
		coord.currentPage = sitemap.getPage(p.page);
	}
	
	//define
	else if(msg.cmd == 'START_SELECT'){
		chrome.tabs.sendMessage(msg.tabId, msg);
	}
	else if(msg.cmd == 'END_SELECT'){
		devtoolPort.postMessage(msg);
	}
	else{
		sendMessage(msg);
	}
});

var print = function(msg){
	chrome.tabs.sendMessage(curTabId, {
		cmd: 'LOG',
		params: msg
	});
}

//Injected scripts will be removed once the tab reload again.
function injectScript(tabId){
	chrome.tabs.executeScript(tabId, {file: "injected/listener.js"});
	chrome.tabs.executeScript(tabId, {file: "lib/jquery/jquery-2.1.1.min.js"}, function() {
		chrome.tabs.executeScript(tabId, {file: "lib/css-selector-generator.js"}, function() {});
		chrome.tabs.executeScript(tabId, {file: "injected/SelectTool.js"}, function() {});
		chrome.tabs.insertCSS(tabId, {file: "injected/injected.css", runAt: "document_end"});
	});
}